function getByte(val) {
  if (!val) { return false; }
  if (!isNaN(Number(val))) { return Number(val); }
  const typeArr = ['b', 'k', 'm', 'g'];
  const valArr = val.split(/(b|k|m|g)/i, 2);
  const index = typeArr.indexOf(valArr[1].toLocaleLowerCase());
  return Number(valArr[0]) * Math.pow(1024, index);
}
function versionIE() {
  const arr = window.navigator.userAgent.match(/MSIE (\d+)\.0;/i);
  return arr ? Number(arr[1]) : NaN;
}
function isObject(obj) {
  return Object.prototype.toString.call(obj) === '[object Object]';
}
// 断网续传方法
function reAjax(options) {
  let lineState = true;
  let resendAjaxOpt = null;
  let resendAjax = null;

  function ajaxFun(opt) {
    return $.ajax({
      ...opt,
      beforeSend(xhr) {
        if (this.resend) {
          resendAjaxOpt = opt;
          resendAjax = xhr;
          const errorFun = this.error || $.noop;
          this.error = (x, status) => {
            errorFun(x, lineState === false ? 'offline' : status);
          };
        }
        typeof opt.beforeSend === 'function' && opt.beforeSend();
      },
      complete(xhr, status) {
        if (this.resend && status === 'success' && lineState) {
          resendAjax = null;
          resendAjaxOpt = null;
        }
        typeof opt.complete === 'function' && opt.complete();
      },
    });
  }
  // 联网
  $(window).off('online.upload').on('online.upload', function () {
    lineState = true;
    if (resendAjaxOpt) {
      ajaxFun(resendAjaxOpt);
      resendAjaxOpt = null;
    }
  }, false);
  // 断网
  $(window).off('offline.upload').on('offline.upload', function () {
    lineState = false;
    if (resendAjax && resendAjax.abort) {
      resendAjax.abort();
      resendAjax = null;
    }
  }, false);
  return ajaxFun(options);
}
function request(opt) {
  const formData = new FormData();
  const data = opt.data || {};

  // 存入formData,  data => 目前只支持是 [ { name: '', value: '' } ]
  data.forEach(v => formData.append(v.name, v.value));

  return reAjax({
    url: opt.url,
    type: 'POST',
    data: formData,
    resend: opt.resend,
    processData: false,
    contentType: false,
    xhr: () => {
      const xhr = $.ajaxSettings.xhr();
      xhr.withCredentials = true;
      xhr.upload && xhr.upload.addEventListener('progress', e => {
        if (e.lengthComputable) {
          const per = Math.floor(100 * (e.loaded / e.total));
          opt.progress(per > 99 ? 99 : per);
        }
      }, false);
      return xhr;
    },
    complete: opt.complete,
    error: opt.error,
    success: opt.success,
  });
}

export default {
  getByte,
  versionIE,
  isObject,
  request,
};
